<template>
  <div v-if="ishead">
    <template v-if="itemdata.lCanOutput === '0'">
      <input type="hidden" :id="itemdata.sField" v-model="itemdata.value" />
    </template>
    <template v-else-if="itemdata.lMustInput === '1' && itemdata.lCanInput === '0'">
      <div class="amap-page-container1">
        <el-amap vid="amapDemo" ref="map" :center="center" :zoom="zoom" :events="events"></el-amap>
      </div>
      <van-field type="textarea" rows="3" :id="itemdata.sField" required disabled :value="itemdata.value"  :error-message="itemdata.errormsg">
        <template #button>
          <van-button plain size="mini" type="info" @click="initPosition">重新定位</van-button>
        </template>
      </van-field>
    </template>
    <template v-else-if="itemdata.lMustInput === '1'">
      <div class="amap-page-container1">
        <el-amap vid="amapDemo" ref="map" :center="center" :zoom="zoom" :events="events"></el-amap>
      </div>
      <van-field type="textarea" rows="3" :id="itemdata.sField" required clearable :value="itemdata.value"  right-icon="location-o" @click-right-icon="openMap(itemdata)">
        <template #button>
          <van-button plain size="mini" type="info" @click="initPosition">重新定位</van-button>
        </template>
      </van-field>
    </template>
    <template v-else-if="itemdata.lCanInput === '0'">
      <div class="amap-page-container1">
        <el-amap vid="amapDemo" ref="map" :center="center" :zoom="zoom" :events="events"></el-amap>
      </div>
      <van-field type="textarea" :id="itemdata.sField" disabled :value="itemdata.value"  :error-message="itemdata.errormsg">
        <template #button>
          <van-button plain size="mini" rows="3" type="info" @click="initPosition">重新定位</van-button>
        </template>
      </van-field>
    </template>
    <template v-else>
      <div class="amap-page-container1">
        <el-amap vid="amapDemo" ref="map" :center="center" :zoom="zoom" :events="events"></el-amap>
      </div>
      <van-field :autosize="{ maxHeight: 50, minHeight: 50 }" rows="3" type="textarea" :id="itemdata.sField" clearable :value="itemdata.value"  right-icon="location-o" @click-right-icon="openMap(itemdata)">
        <template #button>
          <van-button plain size="mini" type="info" @click="initPosition">重新定位</van-button>
        </template>
      </van-field>
    </template>
  </div>
  <div v-else>
    <template v-if="itemdata.lCanOutput === '0'">
      <input type="hidden" :id="itemdata.sField" v-model="itemdata.value" />
    </template>
    <template v-else-if="itemdata.lMustInput === '1' && itemdata.lCanInput === '0'">
      <div class="amap-page-container1">
        <el-amap vid="amapDemo" ref="map" :center="center" :zoom="zoom" :events="events"></el-amap>
      </div>
      <van-field :id="itemdata.sField" required disabled :value="itemdata.value"  :error-message="itemdata.errormsg" />
    </template>
    <template v-else-if="itemdata.lMustInput === '1'">
      <div class="amap-page-container1">
        <el-amap vid="amapDemo" ref="map" :center="center" :zoom="zoom" :events="events"></el-amap>
      </div>
      <van-field type="textarea" placeholder="请选择" :id="itemdata.sField" required clearable :value="itemdata.value"  right-icon="location-o" @click-right-icon="openMap(itemdata, item)" />
    </template>
    <template v-else-if="itemdata.lCanInput === '0'">
      <div class="amap-page-container1">
        <el-amap vid="amapDemo" ref="map" :center="center" :zoom="zoom" :events="events"></el-amap>
      </div>
      <van-field :id="itemdata.sField" disabled :value="itemdata.value"  :error-message="itemdata.errormsg" />
    </template>
    <template v-else>
      <div class="amap-page-container1">
        <el-amap vid="amapDemo" ref="map" :center="center" :zoom="zoom" :events="events"></el-amap>
      </div>
      <van-field type="textarea" placeholder="请选择" :id="itemdata.sField" clearable :value="itemdata.value"  right-icon="location-o" @click-right-icon="openMap(itemdata, item)" />
    </template>
  </div>
</template>
<script>
import Vue from 'vue'
import { Search, List, Cell, PullRefresh, Toast, Tabbar, TabbarItem, Popup, DatetimePicker, ActionSheet, Tab, Tabs, Collapse, CollapseItem, CheckboxGroup, Checkbox, Uploader, Overlay, Loading } from 'vant'
import qs from 'qs'
import wx from 'weixin-js-sdk'
import * as dd from 'dingtalk-jsapi'
import { lazyAMapApiLoaderInstance } from 'vue-amap'
Vue.use(Search).use(List).use(Cell).use(PullRefresh).use(Toast).use(Tabbar).use(TabbarItem).use(Popup).use(DatetimePicker).use(ActionSheet).use(Tab).use(Tabs).use(Collapse).use(CollapseItem).use(CheckboxGroup).use(Checkbox).use(Uploader).use(Overlay).use(Loading)

export default {
  data() {
    let _this = this
    return {
      fromobject: this.$route.query.fromobject,
      fromcardid: this.$route.query.fromcardid,
      zoom: 16,
      // center: [116.413449, 40.050802],
      idobject: this.$route.query.idobject,
      idtemplate: this.$route.query.idtemplate,
      active: 0,
      activeNames: [''],
      activeBodyNams: [''],
      datepickershow: false,
      currentDate: new Date(),
      yearmonthshow: false,
      currentYearMonth: new Date(),
      enumshow: false,
      actions: [],
      clickmodel: {},
      isLoad: false,
      conditionValHidden: '',
      clickfrom: '',
      clickindexName: '',
      clickindex: 0,
      selecteddata: [],
      enumMultishow: false,
      enumMulti: [],
      isDisable: false,
      overlayShow: false,
      saveBs: 'new',
      isPosi: 0,
      mapInstance: '',
      qiandaotime: '',
      place: '',
      consoleInfo: 'aaaaaa</br>',
      map: null,
      gaodeIsSuccess: false,
      godeStatus: "init",
      locationStatus: "init",

      events: {
        init: (o) => {

          this.map = o
          this.gaodeConfig()

          return


          _this.mapInstance = o
          let that = this

          if (_this.isPosi === 0) {
            //console.log("高德定位已开始@@@@@@@@@")
            // lazyAMapApiLoaderInstance.load().then(() => {
            AMap.plugin('AMap.Geolocation', function () {
              var geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,
                timeout: 7000,
                zoomEnable: false,
                dragEnable: false,
                showButton: false,
                buttonOffset: new AMap.Pixel(10, 20),
                zoomToAccuracy: false
              })
              o.addControl(geolocation)
              that.regetlocation(geolocation)
            })
            // })
          }
        }
      },

    }
  },
  props: {
    item: {
      type: Object,
      required: false
    },
    jsondata: {
      type: Object,
      required: false
    },
    itemdata: {
      type: Object,
      required: false
    },
    ishead: {
      type: Boolean,
      default: false
    },
    index: {
      type: Number,
      required: false
    },
    center: {
      type: Array,
      required: false
    }
  },
  mounted: function () {

    this.getEnvironmentalInfo()
    if (this.logintype === 'wxwork' || this.logintype === "dingding" || this.logintype === "wechat") {
      this.getlocation()
    }
    this.qiandaotime = this.currenttime().split(' ')[1].substring(0, 5)
    if (!this.fromobject) {
      this.fromobject = this.idobject
    }
  },
  methods: {

    //重新定位
    initPosition() {
      this.godeStatus = "init"
      this.gaodeConfig()//重新开始高德地图定位
      if (this.logintype === 'wxwork' || this.logintype === "dingding" || this.logintype === "wechat") {
        this.locationStatus = "init"
        this.getlocation()//重新开始签名(微信钉钉)定位
      }
    },

    //高德配置
    gaodeConfig() {
      let that = this
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 7000,
          zoomEnable: false,
          dragEnable: false,
          showButton: false,
          buttonOffset: new AMap.Pixel(10, 20),
          zoomToAccuracy: false
        })

        that.map.addControl(geolocation)
        that.regetlocation(geolocation)
      })

    },

    regetlocation(geolocation) {
      let that = this
      Toast.loading({
        message: '定位中...',
        forbidClick: true,
        duration: 0
      })

      this.godeStatus = "loading"

      geolocation.getCurrentPosition(function (status, result) {
        if (status === 'complete') {
          that.gaodeIsSuccess = true
          that.godeStatus = "success"

          //console.log('高德获取的位置信息*******', result.position, [result.position.lng, result.position.lat])

          that.$emit('distanceInit', [result.position.lng, result.position.lat], "Gaode")
          that.$emit('savePositionInfo', `Gaode${result.position.lng} ${result.position.lat}`, 'gaode')
          Toast.clear()

          that.place = result.formattedAddress
          for (let groupindex in that.jsondata.head) {
            // //console.log('_this.jsondata.head[groupindex].groupvalue', _this.jsondata.head, groupindex)
            let itemgroup = that.jsondata.head[groupindex].groupvalue
            for (let itemindex in itemgroup) {
              let itemdata = itemgroup[itemindex]
              if (itemdata.sUIType === 'map') {
                //console.log("高德写入")
                itemdata.value = result.formattedAddress + '&&' + result.position
              }
            }
          }
        } else {
          // Toast("定位失败")
          that.godeStatus = "fail"
          if (that.locationStatus === "fail" || that.logintype === 'browser') {
            Toast("定位失败")
          }

          //console.log("高德定位失败&&&&&&&&", result)
          setTimeout(() => {
            Toast.clear()
          }, 1000)
        }
      })
    },

    getTicket() {
      const appId = 'wx09830bf23f70b003'
      const appsecret = '4c08a0e7e4f2a013dba8a3c7dc89e903'
      const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appsecret}`
      this.axios({
        url: url
      }).then(res => {
        //console.log('****', res)
      })
    },

    //高德获取详细地址
    getAddress(lng, lat) {
      this.$emit('savePositionInfo', `Weixin ${lng} ${lat}`, 'weixin')
      //console.log(`微信获取的位置信息&&&&&&&&&&&& ${lng} ${lat}`)
      if (this.gaodeIsSuccess) {
        return
      }
      this.$emit('distanceInit', [lng, lat], "Weixin")

      let that = this
      AMap.plugin('AMap.Geocoder', function () {
        var geocoder = new AMap.Geocoder({
          batch: true,
          radius: 200,
          extensions: 'all'
        })
        var lnglat = [lng, lat]
        geocoder.getAddress(lnglat, function (status, result) {
          //console.log('geocoder.getAddress', result)
          if (status === 'complete' && result.info === 'OK') {
            const address = result.regeocode.formattedAddress || ''
            // that.center = lnglat
            that.$emit('update:center', [lng, lat])

            const marker = new AMap.Marker({
              position: new AMap.LngLat(lng, lat) // 经纬度对象，也可以是经纬度构成的一维数组[lng, lat]
            })
            // 将创建的点标记添加到已有的地图实例：
            that.map.add(marker)
            that.map.setFitView()

            // result为对应的地理位置详细信息
            if (that.godeStatus !== "success") {
              for (let groupindex in that.jsondata.head) {
                // //console.log('_this.jsondata.head[groupindex].groupvalue', _this.jsondata.head, groupindex)
                let itemgroup = that.jsondata.head[groupindex].groupvalue
                for (let itemindex in itemgroup) {
                  let itemdata = itemgroup[itemindex]
                  if (itemdata.sUIType === 'map') {
                    //console.log("其他写入")
                    itemdata.value = address + '&' + lnglat.join(',')
                  }
                }
              }
            }

          }
        })
      })

    },

    getEnvironmentalInfo() {
      this.ua = window.navigator.userAgent.toLowerCase()
      this.logintype = 'wechat'
      this.tourl = window.location.href
      this.clttype = 'android'
      if (this.ua.indexOf('iphone') !== -1) {
        this.clttype = 'ios'
      }
      if (this.ua.indexOf('wxwork') !== -1) {
        this.logintype = 'wxwork'

      } else if (this.ua.indexOf('dingtalk') !== -1) {
        this.logintype = 'dingding'

      } else if (this.ua.indexOf('micromessenger') !== -1) {
        this.logintype = 'wechat'

      } else {
        this.logintype = 'browser'
      }

    },



    //判断当前环境
    // getlocation() {

    // if (this.ua.indexOf('wxwork') !== -1) {
    //   logintype = 'wxwork'
    //   this.getSignature()
    // } else if (ua.indexOf('dingtalk') !== -1) {
    //   logintype = 'dingding'
    //   this.getSignature()
    // } else if (ua.indexOf('micromessenger') !== -1) {
    //   logintype = 'wechat'
    //   this.getSignature()
    // } else {
    //   logintype = 'browser'
    // }


    // },

    //获取签名(微信或钉钉)并定位
    getlocation() {
      let _this = this

      const tourl = this.tourl
      const logintype = this.logintype
      const clttype = this.clttype
      let data = {
        url: tourl,
        type: logintype,
        clttype: clttype
      }


      let url = '/api/' + this.idobject + '.getlocation.do'
      Toast.loading({
        message: '定位中...',
        forbidClick: true,
        duration: 0
      })

      this.axios({
        method: 'post',
        url: url,
        data: qs.stringify(data)
      }).then(res => {
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {

          let data = res.data
          if ((logintype === 'wechat' || logintype === 'wxwork')) {
            //console.log("微信定位已开始#########")

            this.consoleInfo += 'in1 ' + logintype + '</br>'
            let configData = {
              beta: true,
              debug: false,
              appId: data.appId,
              timestamp: data.timestamp,
              nonceStr: data.nonceStr,
              signature: data.signature,
              jsApiList: [
                'checkJsApi',
                'getLocation'
              ]
            }
            wx.config(configData)
            wx.ready(function () {
              wx.getLocation({
                isHighAccuracy: true,
                type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                  // _this.consoleInfo += JSON.stringify(res)
                  _this.locationStatus = "success"
                  _this.getAddress(res.longitude, res.latitude)
                  Toast.clear()
                },
                fail: function (err) {
                  _this.locationStatus = "fail"
                  if (_this.godeStatus === "fail") {
                    Toast(`微信定位失败,请检查是否开启位置权限`)
                  }
                  setTimeout(() => {
                    Toast.clear()
                  }, 1000)
                }
              })
            })
          } else if (logintype === 'dingding') {
            //console.log("钉钉定位已开始#########")
            let configData = {
              agentId: data.agentid,
              corpId: data.appId,
              timeStamp: data.timestamp,
              nonceStr: data.nonceStr,
              signature: data.signature,
              type: 0,
              jsApiList: [
                'runtime.info',
                'biz.contact.choose',
                'device.notification.confirm',
                'device.notification.alert',
                'device.notification.prompt',
                'biz.ding.post',
                'biz.util.openLink',
                'device.geolocation.get'
              ]
            }
            dd.config(configData)
            dd.error(function (error) {
              alert(tourl + window.location.href + '  dd error: ' + JSON.stringify(error) + ' -- dd config -- ' + JSON.stringify(configData))
            })
            dd.ready(function () {
              dd.device.geolocation.get({
                targetAccuracy: 200,
                coordinate: 1,
                withReGeocode: false,
                useCache: true,
                onSuccess: function (res) {

                  _this.locationStatus = "success"
                  _this.getAddress(res.longitude, res.latitude)
                  Toast.clear()
                },
                onfail: function (err) {
                  _this.locationStatus = "fail"
                  if (_this.godeStatus === "fail") {
                    Toast(`钉钉定位失败,请检查是否开启位置权限`)
                  }
                  setTimeout(() => {
                    Toast.clear()
                  }, 1000)

                }
              })
            })
          }
        }
      }).catch(function (error) {
        //console.log(`签名catch${error}`)
        // Toast("签名失败")
      }).finally(() => {
        setTimeout(() => {
          Toast.clear()
        }, 2000);

      })

    },

    getlocation_Back() {

      // this.getAddress(111.29008483886719, 23.483417510986328)
      // return

      let _this = this
      let ua = window.navigator.userAgent.toLowerCase()
      let logintype = 'wechat'
      let tourl = window.location.href
      let clttype = 'android'
      if (ua.indexOf('iphone') !== -1) {
        clttype = 'ios'
      }

      if (ua.indexOf('wxwork') !== -1) {
        logintype = 'wxwork'
      } else if (ua.indexOf('dingtalk') !== -1) {
        logintype = 'dingding'
        // tourl = window.location.protocol + '//' + window.location.host + '/vue-common/dist/main'
      } else if (ua.indexOf('micromessenger') !== -1) {
        logintype = 'wechat'
      } else {
        logintype = 'browser'
      }

      let data = {
        url: tourl,
        type: logintype,
        clttype: clttype
      }

      let url = '/api/' + this.idobject + '.getlocation.do'
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })

      this.axios({
        method: 'post',
        url: url,
        data: qs.stringify(data)
      }).then(res => {
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {

          let data = res.data
          if ((logintype === 'wechat' || logintype === 'wxwork')) {
            //console.log("微信定位已开始#########")

            this.consoleInfo += 'in1 ' + logintype + '</br>'
            let configData = {
              beta: true,
              debug: false,
              appId: data.appId,
              timestamp: data.timestamp,
              nonceStr: data.nonceStr,
              signature: data.signature,
              jsApiList: [
                'checkJsApi',
                'getLocation'
              ]
            }
            wx.config(configData)
            // //console.log('config end ', logintype)
            wx.ready(function () {
              // //console.log('ready ', logintype)
              wx.getLocation({
                isHighAccuracy: true,
                type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                  // _this.consoleInfo += JSON.stringify(res)

                  _this.getAddress(res.longitude, res.latitude)
                  Toast.clear()
                },
                fail: function (err) {
                  Toast('定位失败')

                  _this.consoleInfo += window.location.href
                  // alert('请检查定位是否已经打开!' + JSON.stringify(err) + ' --- config 1data --- ' + JSON.stringify(configData))
                }
              })
            })
          } else if (logintype === 'dingding') {
            let configData = {
              agentId: data.agentid,
              corpId: data.appId,
              timeStamp: data.timestamp,
              nonceStr: data.nonceStr,
              signature: data.signature,
              type: 0,
              jsApiList: [
                'runtime.info',
                'biz.contact.choose',
                'device.notification.confirm',
                'device.notification.alert',
                'device.notification.prompt',
                'biz.ding.post',
                'biz.util.openLink',
                'device.geolocation.get'
              ]
            }
            dd.config(configData)
            dd.error(function (error) {
              alert(tourl + window.location.href + '  dd error: ' + JSON.stringify(error) + ' -- dd config -- ' + JSON.stringify(configData))
            })
            dd.ready(function () {
              dd.device.geolocation.get({
                targetAccuracy: 200,
                coordinate: 1,
                withReGeocode: false,
                useCache: true,
                onSuccess: function (res) {
                  // //console.log('location res -- dd -- ' + res)
                  // _this.consoleInfo += JSON.stringify(res)
                  _this.getAddress(res.longitude, res.latitude)
                  Toast.clear()
                },
                onfail: function (err) {
                  _this.consoleInfo += JSON.stringify(err)
                  Toast('定位失败')
                  // //console.log('location error -- dd -- ' + JSON.stringify(err))
                  // alert('请检查定位是否已经打开!')
                }
              })
            })
          } else {
            AMap.plugin('AMap.Geolocation', function () {
              var geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,
                timeout: 5000,
                zoomEnable: false,
                dragEnable: false,
                showButton: false,
                buttonOffset: new AMap.Pixel(10, 20),
                zoomToAccuracy: true
              })
              geolocation.getCurrentPosition(function (status, result) {
                if (status === 'complete') {
                  // _this.consoleInfo = 'location res -- amap -- ' + JSON.stringify(result)
                  //console.log('geolocation.getCurrentPosition', result)
                  _this.getAddress(result.position.lng, result.position.lat)
                  Toast.clear()
                  // //console.log('location res -- amap -- ', result)
                  // //console.log(result.position + '-------')
                  // //console.log(result.formattedAddress)
                  // _this.center =
                  /* o.center = result.position
                  _this.place = result.formattedAddress
                  for (let groupindex in _this.jsondata.head) {
                    let itemgroup = _this.jsondata.head[groupindex].groupvalue
                    for (let itemindex in itemgroup) {
                      let itemdata = itemgroup[itemindex]
                      if (itemdata.sUIType === 'map') {
                        itemdata.value = result.formattedAddress + '&' + result.position
                      }
                    }
                  } */
                  _this.consoleInfo += '</br>jsondata --- ' + JSON.stringify(_this.jsondata)
                } else {
                  Toast('定位失败')
                  // alert(JSON.stringify(result))
                  // //console.log('location error -- amap -- ', JSON.stringify(result))
                }
              })
            })
          }
        }
      }).catch(function (error) {
        // alert('error -all- ' + error)
        this.consoleInfo = 'error -all- ' + error
      }).finally(() => {
        setTimeout(() => {
          Toast.clear()
        }, 2000);

      })
    },

    currenttime() {
      let d = new Date()
      let year = d.getFullYear()
      let month = this.change(d.getMonth() + 1)
      let day = this.change(d.getDate())
      let hour = this.change(d.getHours())
      let minute = this.change(d.getMinutes())
      let second = this.change(d.getSeconds())
      let time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
      return time
    },
    change(t) {
      if (t < 10) {
        return '0' + t
      } else {
        return t
      }
    },
    openMap(data, item) {
      let name = ''
      //  alert(JSON.stringify(item.groupvalue))
      let gv = item.groupvalue
      //  alert(gv.length)
      for (let i = 0; i < gv.length; i++) {
        if (gv[i].sField === 'sname') {
          name = gv[i].value
          break
        }
      }
      // alert("name::" + name)
      this.$router.push({
        name: 'map4common',
        params: {
          sval: this.jsondata.head,
          svalmap: data,
          curName: name
        }
      })
    }
  }
}
</script>
<style>
.fieldgroup_title {
  text-align: left;
  margin: 0px;
  padding: 25px 15px 15px;
  color: rgba(69, 90, 100, 0.6);
  font-weight: normal;
  font-size: 14px;
}

.amap-page-container1 {
  height: 30vh;
  width: 100%;
  box-sizing: border-box;
  position: relative;
}

.amap-page-container1 .bottom-mask {
  position: absolute;
  width: 100%;
  height: 26px;
  background: #fff;
  bottom: 0;
  left: 0;
  z-index: 99999;
}
</style>
